package com.qunar.wan.tools.pager.dialect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Dialect接口的MySQL实现，用于提供物理分页。
 * <p/>
 * 基于@author fanyong.kong修改
 *
 * @author yong.chen
 */
public class MySQLDialect implements Dialect {
    private Logger logger = LoggerFactory.getLogger(getClass());

    // SQL结束标记.
    protected static final String SQL_END_DELIMITER = ";";

    public String getLimitString(String sql, int offset, int limit) {

        if (sql.endsWith(SQL_END_DELIMITER)) {
            CharSequence _sql = sql.subSequence(0, sql.length() - SQL_END_DELIMITER.length());
            return append(new StringBuilder(_sql), offset, limit).append(SQL_END_DELIMITER).toString();
        }

        return append(new StringBuilder(sql), offset, limit).toString();
    }

    private StringBuilder append(StringBuilder builder, int offset, int limit) {
        if (offset > 1000 || limit > 1000) {
            logger.warn("SQL中存在limit||offset >1000情况，将自动调整为1000,原SQL={}", String.format("%s limit %s offset %s", builder.toString(), limit, offset));
        }

        if (limit < 1000) {
            builder.append(" limit ").append(limit);
        } else {

            builder.append(" limit ").append(1000);
        }

        //限定查询结果偏移1000条以内的数据
        if (offset > 0) {
            if (offset <= 1000) {
                builder.append(" offset ").append(offset);
            } else {
                builder.append(" offset ").append(1000);
            }
        }
        return builder;
    }
}
